package org.robot.scm.utils;

import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliSpeakUtil {

    private static final NlsClient CLIENT;

    static {
        String accessKeyId = "LTAI5tKDkcURLQY4PJeFXEK8";
        String accessKeySecret = "fDrxwdtdXLlGbjp0dagZ1Bp3wpqMtD";
        AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
        try {
            accessToken.apply();
            CLIENT = new NlsClient("wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1", accessToken.getToken());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static SpeechSynthesizerListener initListener() {
        return new SpeechSynthesizerListener() {

            final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

            @SneakyThrows
            @Override
            public void onComplete(SpeechSynthesizerResponse speechSynthesizerResponse) {
                byte[] bytes = outStream.toByteArray();
                AudioInputStream audioContent = AudioSystem.getAudioInputStream(new ByteArrayInputStream(bytes));
                AudioSoundUtil.playSound(audioContent);
            }

            @Override
            public void onFail(SpeechSynthesizerResponse speechSynthesizerResponse) {

            }

            @SneakyThrows
            @Override
            public void onMessage(ByteBuffer byteBuffer) {
                byte[] bytesArray = new byte[byteBuffer.remaining()];
                byteBuffer.get(bytesArray, 0, bytesArray.length);
                outStream.write(bytesArray);
            }
        };
    }

    @SneakyThrows
    public static void speak(String content) {
        String appKey = "Kc4xMV7IFYxsOjmO";
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(CLIENT, initListener());
        //创建实例，建立连接。
        synthesizer.setAppKey(appKey);
        //设置返回音频的编码格式
        synthesizer.setFormat(OutputFormatEnum.WAV);
        //设置返回音频的采样率
        synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
        //发音人
        synthesizer.setVoice("zhiyue");
        // 音量100%
        synthesizer.setVolume(100);
        //设置用于语音合成的文本
        synthesizer.setText(content);
        // 是否开启字幕功能（返回相应文本的时间戳），默认不开启，需要注意并非所有发音人都支持该参数。
        synthesizer.addCustomedParam("enable_subtitle", false);
        //此方法将以上参数设置序列化为JSON格式发送给服务端，并等待服务端确认。
        synthesizer.start();
        //等待语音合成结束
        synthesizer.waitForComplete();
        synthesizer.close();
    }


    public static void main(String[] args) {
        speak("现在时间是16:58, 您的血糖值为: 6.8 摩尔每升");
    }
}
